package com.wenzhoujie.fragment;

import java.util.HashMap;
import java.util.Map;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.lingou.www.R;
import com.wenzhoujie.config.O2oConfig;
import com.wenzhoujie.constant.ApkConstant;
import com.wenzhoujie.jshandler.AppJsHandler;
import com.wenzhoujie.library.title.SDTitle;
import com.wenzhoujie.library.utils.SDBase64;
import com.wenzhoujie.library.utils.SDViewUtil;
import com.wenzhoujie.library.utils.UrlLinkBuilder;
import com.wenzhoujie.utils.IocUtil;
import com.wenzhoujie.utils.SDHandlerUtil;
import com.wenzhoujie.utils.ViewInject;

/**
 * WebView fragment
 * 
 * @author js02
 * 
 */
public class WebViewFragment extends BaseFragment
{

	@ViewInject(id = R.id.frag_webview_pgb_progress)
	private ProgressBar mPgbProgress = null;

	@ViewInject(id = R.id.frag_webview_wv_webview)
	protected WebView mWeb = null;
	
	protected String mStrUrl = null;
	private String mStrHtmlContent = null;
	protected String mStrReferer = null;
	protected String mStrTitle = null;

	private boolean isScaleToShowAll = false;
	private boolean isSupportZoom = true;
	private boolean isSupportZoomControls = false;
	
	protected WebViewFragmentListener mListener;
	protected SDTitle mTitle;
	
	protected EnumProgressMode mProgressMode = EnumProgressMode.NONE;
	protected EnumWebviewHeightMode mWebviewHeightMode = EnumWebviewHeightMode.WRAP_CONTENT;

	public void setmListener(WebViewFragmentListener mListener)
	{
		this.mListener = mListener;
	}
	
	public void setmProgressMode(EnumProgressMode mProgressMode)
	{
		this.mProgressMode = mProgressMode;
		changeProgressMode();
	}
	
	public void setSupportZoomControls(boolean isSupportZoomControls)
	{
		this.isSupportZoomControls = isSupportZoomControls;
	}

	public void setSupportZoom(boolean isSupportZoom)
	{
		this.isSupportZoom = isSupportZoom;
	}

	public void setScaleToShowAll(boolean isScaleToNormal)
	{
		this.isScaleToShowAll = isScaleToNormal;
	}

	public void setUrl(String url)
	{
		this.mStrUrl = wrapperUrl(url);
	}
	
	private String wrapperUrl(String url)
	{
		String resultUrl = putSessionId(url);
		resultUrl = putPageType(resultUrl);
		resultUrl = putRefId(resultUrl);
		return resultUrl;
	}

	private String putPageType(String url)
	{
		if (TextUtils.isEmpty(url))
		{
			url = new UrlLinkBuilder(url).add("page_type", "app").build();
		}
		return url;
	}

	private String putRefId(String url)
	{
		String refId = O2oConfig.getRefId();
		if (!TextUtils.isEmpty(url) && !TextUtils.isEmpty(refId))
		{
			url = new UrlLinkBuilder(url).add("r", SDBase64.encode(refId)).build();
		}
		return url;
	}

	private String putSessionId(String url)
	{
		// 如果是域名的url，添加session
		if (url != null && url.contains(ApkConstant.SERVER_API_URL_MID))
		{
			String sessionId = O2oConfig.getSessionId();
			if (sessionId != null)
			{
				url = new UrlLinkBuilder(url).add("sess_id", sessionId).build();
			}
		}
		return url;
	}

	public void setTitle(String title) {
		this.mStrTitle = title;
		if (mTitle != null) {
			mTitle.setMiddleTextTop(title);
		}
	}
	
	public void setHtmlContent(String htmlContent)
	{
		this.mStrHtmlContent = htmlContent;
	}

	public void setReferer(String referer)
	{
		this.mStrReferer = referer;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		View view = inflater.inflate(R.layout.frag_webview, container, false);
		IocUtil.initInjectedView(this, view);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState)
	{
		init();
		super.onViewCreated(view, savedInstanceState);
	}

	private void init()
	{
		changeWebviewHeightMode();
		initWebView();
		initFinish();
		changeProgressMode();
		startLoadData();
	}

	public void startLoadData()
	{
		if (mStrHtmlContent != null)
		{
			loadHtmlContent(mStrHtmlContent);
			return;
		}

		if (mStrUrl != null)
		{
			loadUrl(mStrUrl, mWeb);
			return;
		}

	}

	protected void changeProgressMode()
	{
		if (mProgressMode != null && mPgbProgress != null)
		{
			switch (mProgressMode)
			{
			case HORIZONTAL:
				SDViewUtil.show(mPgbProgress);
				break;
			case NONE:
				SDViewUtil.hide(mPgbProgress);
				break;

			default:
				break;
			}
		}
	}
	
	public void setmWebviewHeightMode(EnumWebviewHeightMode mWebviewHeightMode)
	{
		this.mWebviewHeightMode = mWebviewHeightMode;
		changeWebviewHeightMode();
	}

	protected void changeWebviewHeightMode()
	{
		if (mWeb != null)
		{
			ViewGroup.LayoutParams paramsOld = mWeb.getLayoutParams();
			if (paramsOld != null && paramsOld instanceof LinearLayout.LayoutParams)
			{
				LinearLayout.LayoutParams params = null;
				switch (mWebviewHeightMode)
				{
				case WRAP_CONTENT:
					params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
					break;
				case MATCH_PARENT:
					params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
					break;

				default:
					break;
				}
				mWeb.setLayoutParams(params);
			}
		}
	}
	
	private void initWebView()
	{
		initSetting();
		addJavascriptInterface();
		mWeb.setWebViewClient(new ProjectDetailWebviewActivity_WebViewClient());
		mWeb.setWebChromeClient(new ProjectDetailWebviewActivity_WebChromeClient());
	}

	protected void addJavascriptInterface()
	{
		// 详情回调处理
		AppJsHandler detailHandler = new AppJsHandler(getActivity())
		{
			@Override
			@JavascriptInterface
			public void page_title(final String title)
			{
				SDHandlerUtil.runOnUiThread(new Runnable()
				{

					@Override
					public void run()
					{
						setTitle(title);
					}
				});
			}
		};
		mWeb.addJavascriptInterface(detailHandler, detailHandler.getName());
	}
	
	@SuppressLint("SetJavaScriptEnabled")
	private void initSetting()
	{
		WebSettings settings = mWeb.getSettings();
		settings.setJavaScriptEnabled(true);
		settings.setCacheMode(WebSettings.LOAD_DEFAULT);
		settings.setSupportZoom(isSupportZoom);
		settings.setBuiltInZoomControls(isSupportZoomControls);
		settings.setAppCacheEnabled(true);
		settings.setDomStorageEnabled(true);
		// 设置自适应屏幕
		if (isScaleToShowAll)
		{
			settings.setUseWideViewPort(true);
			settings.setLoadWithOverviewMode(true);
		}
	}

	private void loadHtmlContent(String htmlContent)
	{
		if (htmlContent != null)
		{
			mWeb.loadDataWithBaseURL("about:blank", htmlContent, "text/html", "utf-8", null);
		}
	}

	private void loadUrl(String url, WebView webView)
	{
		boolean shouldLoad = true;
		if (mListener != null)
		{
			if (mListener.onLoadUrl(webView, url)) // 事件被消费
			{
				shouldLoad = false;
			}
		}

		if (shouldLoad)
		{
			if (!TextUtils.isEmpty(url))
			{
				if (!TextUtils.isEmpty(mStrReferer))
				{
					Map<String, String> mapHeader = new HashMap<String, String>();
					mapHeader.put("Referer", mStrReferer);
					webView.loadUrl(url, mapHeader);
				} else
				{
					webView.loadUrl(url);
				}
			}
		}
	}

	class ProjectDetailWebviewActivity_WebViewClient extends WebViewClient
	{

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url)
		{
			loadUrl(url, view);
			return true;
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon)
		{

			super.onPageStarted(view, url, favicon);
		}

		@Override
		public void onPageFinished(WebView view, String url)
		{

			super.onPageFinished(view, url);
		}
	}

	class ProjectDetailWebviewActivity_WebChromeClient extends WebChromeClient
	{

		@Override
		public void onProgressChanged(WebView view, int newProgress)
		{
			if (newProgress == 100)
			{
				mPgbProgress.setVisibility(View.GONE);
			} else
			{
				if (mPgbProgress.getVisibility() == View.GONE)
				{
					mPgbProgress.setVisibility(View.VISIBLE);
				}
				mPgbProgress.setProgress(newProgress);
			}
			super.onProgressChanged(view, newProgress);
		}
	}

	public void onGoBack()
	{
		mWeb.goBack();
	}
	public boolean canGoBack()
	{ 
		return mWeb.canGoBack(); 
	}

	protected void initFinish()
	{
		if (mListener != null)
		{
			mListener.onInitFinish(mWeb);
		}
	}
	
	@Override
	public void onPause()
	{
		mWeb.onPause();
		super.onPause();
	}

	@Override
	public void onResume()
	{
		mWeb.onResume();
		super.onResume();
	}

	@Override
	public void onDestroy()
	{
		if (mWeb != null)
		{
			mWeb.destroy();
			mWeb = null;
		}
		super.onDestroy();
	}
	
	/*@Override
	public void onDestroy()
	{
		mWeb.clearCache(false);
		mWeb.removeAllViews();
		mWeb.destroy();
		super.onDestroy();
	}*/
	
	public interface WebViewFragmentListener
	{
		public void onInitFinish(WebView webView);

		public boolean onLoadUrl(WebView webView, String url);
	}
	
	public enum EnumProgressMode
	{
		HORIZONTAL, NONE
	}

	public enum EnumWebviewHeightMode
	{
		WRAP_CONTENT, MATCH_PARENT
	}

}